package org.msn.util;

import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;

public class GenerateUtil {

    public synchronized static int generateAvailableHostPort() {
        int port;

        do {
            port = generatePort();
        } while (!isPortUsing("127.0.0.1", port));

        return port;
    }

    private static int generatePort() {
        int max = 65535;
        int min = 2000;

        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    private static boolean isPortUsing(String host, int port) {
        try {
            InetAddress inetAddress = InetAddress.getByName(host);
            Socket socket = new Socket(inetAddress, port);
            socket.close();
            return true;
        } catch (Exception e) {
        }

        return false;
    }
}